package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemActionManager;
import com.fish.anne.model.SystemAction;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemActionAction extends BaseAction implements Preparable {
    private SystemActionManager systemActionManager;
    private List systemActions;
    private SystemAction systemAction;
    private Long  actionId;

    public void setSystemActionManager(SystemActionManager systemActionManager) {
        this.systemActionManager = systemActionManager;
    }

    public List getSystemActions() {
        return systemActions;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemActionId = getRequest().getParameter("systemAction.actionId");
            if (systemActionId != null && !systemActionId.equals("")) {
                systemAction = systemActionManager.get(new Long(systemActionId));
            }
        }
    }

    public String list() {
        systemActions = systemActionManager.getAll();
        return SUCCESS;
    }

    public void setActionId(Long  actionId) {
        this. actionId =  actionId;
    }

    public SystemAction getSystemAction() {
        return systemAction;
    }

    public void setSystemAction(SystemAction systemAction) {
        this.systemAction = systemAction;
    }

    public String delete() {
        systemActionManager.remove(systemAction.getActionId());
        saveMessage(getText("systemAction.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (actionId != null) {
            systemAction = systemActionManager.get(actionId);
        } else {
            systemAction = new SystemAction();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemAction.getActionId() == null);

        systemActionManager.save(systemAction);

        String key = (isNew) ? "systemAction.added" : "systemAction.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}